/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.service.impl;

import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.emergency.domain.ContingencyPlan;
import com.koron.emergency.domain.EmergencyResponse;
import com.koron.emergency.domain.NoticeBean;
import com.koron.emergency.mapper.ContingencyPlanMapper;
import com.koron.emergency.mapper.EmergencyResponseMapper;
import com.koron.emergency.service.api.EmergencyResponseService;
import com.koron.emergency.util.BusinessCode;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import com.koron.workflow.bean.MessageEntity;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmergencyResponseServiceImpl implements EmergencyResponseService {
    private final static  Logger logger = LoggerFactory.getLogger(EmergencyResponseServiceImpl.class);
    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;

    @Value("${app.orgCode}")
    private String orgCode;

    @Value("${login.server}")
    private String server;

    @Autowired
    private Util util;

    @Override
    public MessageBean<Integer> save(StaffBean user, EmergencyResponse bean, List<NoticeBean> noticeList) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(bean.getCorpCode())) {
                msg.setCode(BusinessCode.EMERGENCYRESPONSE_EMPTY_CORP.getCode());
                msg.setDescription(BusinessCode.EMERGENCYRESPONSE_EMPTY_CORP.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getResponseLevel())) {
                msg.setCode(BusinessCode.EMERGENCYRESPONSE_EMPTY_RESPONSELEVEL.getCode());
                msg.setDescription(BusinessCode.EMERGENCYRESPONSE_EMPTY_RESPONSELEVEL.getDescription());
                return msg;
            }
            Integer value = 0;
            if (StringUtils.isEmpty(bean.getUrl())) {
                bean.setUrl(server + "?url=http://localhost:9999/web/index.html#/businessManageHome/emergencyResponse");
            }
            bean.setStatus(0);
            if (StringUtils.isEmpty(bean.getId())) {
                //新增
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                value = factory.getMapper(EmergencyResponseMapper.class).insert(bean);
                if (value > 0) {
                    if (null != noticeList && noticeList.size() > 0) {
                        for (NoticeBean noticeBean : noticeList) {
                            noticeBean.setEmergencyResponseId(bean.getId());
                            noticeBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                            if (StringUtils.isEmpty(noticeBean.getResponseLevel())) {
                                noticeBean.setResponseLevel(bean.getResponseLevel());
                            }
                            if (StringUtils.isEmpty(noticeBean.getResponseLevelName())) {
                                noticeBean.setResponseLevelName(bean.getResponseLevelName());
                            }
                        }
                        value = factory.getMapper(EmergencyResponseMapper.class).batchInsert(noticeList);
                    }

                }
            } else {
                //修改
                EmergencyResponse entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.EMERGENCYRESPONSE_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.EMERGENCYRESPONSE_NOT_EXIST.getDescription());
                    return msg;
                }
                value = factory.getMapper(EmergencyResponseMapper.class).update(bean);
                // 先删除原有的通知信息
                factory.getMapper(EmergencyResponseMapper.class).deleteNotice(bean.getId());
                if (null != noticeList && noticeList.size() > 0) {
                    for (NoticeBean noticeBean : noticeList) {
                        if (StringUtils.isEmpty(noticeBean.getResponseLevel())) {
                            noticeBean.setResponseLevel(bean.getResponseLevel());
                        }
                        if (StringUtils.isEmpty(noticeBean.getResponseLevelName())) {
                            noticeBean.setResponseLevelName(bean.getResponseLevelName());
                        }
                        noticeBean.setEmergencyResponseId(bean.getId());
                        noticeBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                    }
                    value = factory.getMapper(EmergencyResponseMapper.class).batchInsert(noticeList);
                }
            }
            if (value > 0) {
                Port port = getPort();
                // 根据应急预案id获取应急预案下的响应等级
                if (null != noticeList && noticeList.size() > 0) {
                    for (NoticeBean noticeBean : noticeList) {
                        StringBuilder text = new StringBuilder();
                        text.append(noticeBean.getContent()).append("。应急事件总结：").append(bean.getSummary()).append("。");
                        List<Message> messageList = new ArrayList<>();
                        List<String> emails = new ArrayList<>();
                        if (StringUtils.isNotEmpty(noticeBean.getNoticeObject())) {
                            // 获取响应等级要通知的组织
                            String[] deptCodeList = noticeBean.getNoticeObject().split("[,，]");
                            for (String deptCode : deptCodeList) {
                                // 获取组织下的人员信息
                                List<StaffBean> list = port.depstaff(orgCode, deptCode, 1).getData();
                                if (null != list && list.size() > 0) {
                                    for (StaffBean staffBean : list) {
                                        Message message = new Message();
                                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                        message.setAddTime(bean.getUpdateTime());
                                        message.setIsRemove(0);
                                        message.setIsRead(0);
                                        message.setAddUser(bean.getUpdateUser());
                                        message.setUpdateUser(bean.getUpdateUser());
                                        message.setUpdateTime(bean.getUpdateTime());
                                        message.setTitle("您有一项新的事故快报待查收");
                                        message.setContent(text.toString());
                                        message.setReceiverCode(staffBean.getCode());
                                        messageList.add(message);
                                    }
//                                    // 获取人员的邮箱
//                                    emails.addAll(list.stream().map(staffBean -> staffBean.getEmail()).collect(Collectors.toList()));
                                }
                            }
                        }
                        if (StringUtils.isNotEmpty(noticeBean.getExtraObject())) {
                            // 获取要通知的人员
                            String[] staffCodeList = noticeBean.getExtraObject().split("[,，]");
                            for (String staffCode : staffCodeList) {
                                Message message = new Message();
                                message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                message.setAddTime(bean.getUpdateTime());
                                message.setIsRemove(0);
                                message.setIsRead(0);
                                message.setAddUser(bean.getUpdateUser());
                                message.setUpdateUser(bean.getUpdateUser());
                                message.setUpdateTime(bean.getUpdateTime());
                                message.setTitle("您有一项新的事故快报待查收");
                                message.setContent(text.toString());
                                message.setReceiverCode(staffCode);
                                messageList.add(message);
                                // 获取人员信息
//                                List<StaffBean> list = port.staff(staffCode, null).getData();
//                                if (null != list && list.size() > 0) {
//                                    if (StringUtils.isNotEmpty(list.get(0).getEmail())) {
//                                        // 获取人员邮箱
//                                        emails.add(list.get(0).getEmail());
//                                    }
//                                }
                            }
                        }
//                        if (null != emails && emails.size() > 0) {
//                            StringBuilder text = new StringBuilder();
//                            text.append(noticeBean.getContent()).append("。应急事件总结：").append(bean.getSummary()).append("。");
//                            SendEmail.complexMailSend(emails, text.toString(), "应急事件通知", bean.getUrl(), null);
//                        }

                        if (null != messageList && messageList.size() > 0) {
                            factory.getMapper(MessageMapper.class).batchInsert(messageList);
                        }
                    }
                }
                factory.close();
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription(BusinessCode.SUCCESS.getDescription());
                msg.setData(value);
                return msg;
            } else {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close();
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(StaffBean user, String id) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        SessionFactory factory = null;
        try {
            factory = new SessionFactory();
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription(BusinessCode.EXCEPTION.getDescription());
                return msg;
            }
            EmergencyResponse entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.EMERGENCYRESPONSE_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.EMERGENCYRESPONSE_NOT_EXIST.getDescription());
                return msg;
            }
            entity.setStatus(1);
            Integer value = factory.getMapper(EmergencyResponseMapper.class).update(entity);
            if (value > 0) {
                factory.close();
                msg.setData(value);
                return msg;
            } else {
                msg.setData(value);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<EmergencyResponse> queryOne(String id) {
        MessageBean<EmergencyResponse> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询应急响应详情成功", EmergencyResponse.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            EmergencyResponse entity = factory.getMapper(EmergencyResponseMapper.class).queryOne(id);
            List<NoticeBean> beanList = factory.getMapper(EmergencyResponseMapper.class).queryNotice(id);
            entity.setNoticeList(beanList);
            getNames(entity);
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<EmergencyResponse>> list(String corpCode, Integer start, Integer rows) {
        MessageBean<DataBean<EmergencyResponse>> msg = new MessageEntity<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<EmergencyResponse> list = factory.getMapper(EmergencyResponseMapper.class).queryByCondition(corpCode, start, rows);
            Integer totalNumber = factory.getMapper(EmergencyResponseMapper.class).countByCondition(corpCode);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<EmergencyResponse> dataBean = new DataBean<>();
            list.forEach(item -> getNames(item));
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取应急响应列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<EmergencyResponse> exportList(StaffBean user, String corpCode) {
        try (SessionFactory factory = new SessionFactory()) {
            List<EmergencyResponse> list = factory.getMapper(EmergencyResponseMapper.class).queryByCondition(corpCode, null, null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list.forEach(bean -> {
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpCodeName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                    if (StringUtils.isNotEmpty(bean.getContingencyPlanId())) {
                        ContingencyPlan plan = factory.getMapper(ContingencyPlanMapper.class).queryOne(bean.getContingencyPlanId());
                        if (null != plan) {
                            bean.setContingencyPlanName(plan.getContingencyPlanName());
                        }
                    }
                    if (null != bean.getBeginTime()) {
                        bean.setBeginTimeStr(sdf.format(bean.getBeginTime()));
                    }
                    if (null != bean.getEndTime()) {
                        bean.setEndTimeStr(sdf.format(bean.getEndTime()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    private void getNames(EmergencyResponse bean) {
        if (null != bean) {
            try (SessionFactory factory = new SessionFactory()) {
                if (StringUtils.isNotEmpty(bean.getContingencyPlanId())) {
                    ContingencyPlan plan = factory.getMapper(ContingencyPlanMapper.class).queryOne(bean.getContingencyPlanId());
                    if (null != plan) {
                        bean.setContingencyPlanName(plan.getContingencyPlanName());
                    }
                }
            }
        }
    }

    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appid);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }
}
